package com.exonline.back.controller.pay;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.exonline.commons.alipay.config.AlipayUtils;
import com.exonline.commons.entity.Courses;
import com.exonline.commons.entity.Student;
import com.exonline.commons.dao.DaoImpl;
import com.exonline.commons.dao.IDao;
import com.exonline.commons.utils.TokenUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @desc 支付模块m层
 * @author hbrj
 */
public class PayService {
    /**
     * @desc 1.支付方法,进行订单支付,调用支付宝支付请求网关
     * @author hbrj
     */
    IDao<Courses> dao = new DaoImpl();
    public void doPay(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.初始化支付信息
        String info = req.getParameter("info");
        String cid = TokenUtils.getCid(info);
        String sid = TokenUtils.getSid(info);
        String WIDsubject = "";
        String WIDtotalAmount = null;
        String body = "";
        String cname = "";
        String sname = "";
        try {
            Courses courses = dao.queryForObject("select * from courses where id = ?", new BeanHandler<>(Courses.class), cid);
            cname = courses.getCname();
            sname = dao.queryForObject("select * from student where id = ?", new BeanHandler<>(Student.class), sid).getSname();
            WIDsubject = courses.getCname();
            WIDtotalAmount = courses.getCprice();
        } catch (SQLException e) {
            throw new RuntimeException("用户支付时参数错误或不存在此课程"+e.getMessage(),e);
        }

        String WIDout_trade_no =IdUtil.simpleUUID();

        if(WIDout_trade_no!=null){
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(WIDout_trade_no);
            // 订单名称，必填
            String subject = new String(WIDsubject);
            System.out.println(subject);
            // 付款金额，必填
            String total_amount=new String(WIDtotalAmount);
            // 商品描述，可空
            if (req.getParameter("widbody")!=null) {
                body = new String(req.getParameter("widbody"));
            }
            // 超时时间 可空
            String timeout_express="10m";
            // 销售产品码 必填
            String product_code="FAST_INSTANT_TRADE_PAY";
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(AlipayUtils.URL, AlipayUtils.APPID, AlipayUtils.RSA_PRIVATE_KEY, AlipayUtils.FORMAT, AlipayUtils.CHARSET, AlipayUtils.ALIPAY_PUBLIC_KEY, AlipayUtils.SIGNTYPE);
            AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
            AlipayTradePagePayRequest alipay_page_request=new AlipayTradePagePayRequest();
            // 封装请求支付信息
            AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
            AlipayTradePagePayModel page_model=new AlipayTradePagePayModel();

            page_model.setOutTradeNo(out_trade_no);
            page_model.setSubject(subject);
            page_model.setTotalAmount(total_amount);
            page_model.setBody(body);
            page_model.setTimeoutExpress(timeout_express);
            page_model.setProductCode(product_code);
            alipay_page_request.setBizModel(page_model);

            alipay_page_request.setNotifyUrl(AlipayUtils.notify_url);
            alipay_page_request.setReturnUrl(AlipayUtils.return_url);


            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
            model.setTimeoutExpress(timeout_express);
            model.setProductCode(product_code);
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(AlipayUtils.notify_url);
            // 设置同步地址
            alipay_request.setReturnUrl(AlipayUtils.return_url);

            try {
                if (WIDtotalAmount.startsWith("0")) {
                    //1.2若支付订单免费,直接将此课程放入学生学习表(studentcourses)
                    dao.updateWithTransaction("INSERT INTO studentcourses(id,sid,cid) VALUES(?,?,?)", IdUtil.simpleUUID(),sid, cid);
                    resp.sendRedirect("支付成功回调地址");
                    return;
                }else {
                    //1.3生成订单记录,状态设置为未支付.
                    dao.updateWithTransaction("INSERT INTO orders(id,cid,sid,status) VALUES(?,?,?,?)", WIDout_trade_no,cid, sid,0);
//                    dao.updateWithTransaction("INSERT INTO studentcourses(id,sid,cid) VALUES(?,?,?)", IdUtil.simpleUUID(),sid, cid);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            //form表单生产
            String form = "";
            try {
                // 调用SDK生成表单
                form = client.pageExecute(alipay_page_request).getBody();
                resp.setContentType("text/html;charset=" + AlipayUtils.CHARSET);
                resp.getWriter().write(form);//直接将完整的表单html输出到页面
                resp.getWriter().flush();
                resp.getWriter().close();
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }


    }
}
